<!--

Copyright (c) 2011 Metaaps SRL(U)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <title>Play Map - Continuous Example</title>

    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/themes/smoothness/jquery-ui.css" type="text/css" media="all" />
    <style type="text/css">
        body { height: 100%; margin: 0px; padding: 10px; }
        #map_canvas { height: 400px; width: 700px; }
        #options { height: 400px; width: 300px; }
        #options > div { margin: 10px; padding: 10px; border: 1px grey solid; }
        #options p { margin: 10px 0px; }
        ul.smallIndent {list-style-position: inside; list-style-type: none; padding: 0px 0px; font-size: 0.9em;}
    </style>

    <style>
        #toolbar {
                padding: 10px 4px;
                font-size: 12px;
                width: 100%;
        }
        #toolbar > #time {
            float: right;
        }
    </style>

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>

    <!-- Google Maps API javascript -->
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?libraries=geometry&sensor=false"></script>
    <script type="text/javascript" src="../js/playMap.js"></script>

    <!-- Initialize visualization -->
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
        google.load('visualization', '1', {});
    </script>

  </head>

<body>

    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">
        Your web browser must have JavaScript enabled
        in order for this application to display correctly.
      </div>
    </noscript>

    <p class="ui-widget-header ui-corner-all">Continuous PlayMap<a href="./discrete.html" target="_top" style="float:right;">Go To Discrete PlayMap</a></p>
    <p>This example demonstrates the use of PlayMap with a Continuous player, that is to stay a continuous timed refresh of
        geographical information data, with the possibility to interpolate positions between geometry values and leave a trace.<br>
        Animation can be played back and forth as with a video player.
    </p>

    <table id="demotable">
        <tr>
            <td><div id="map_canvas"></div></td>
            <td>
                <div id="options">
                    <div><p>Select Example:</p><select id="example"></select></div>
                    <div><a class="a2a_dd" href="http://www.addtoany.com/share_save"><img src="http://static.addtoany.com/buttons/share_save_171_16.png" width="180" height="16" border="0"  style="margin-top: 10px;" alt="Share/Save/Bookmark"/></a><script type="text/javascript">a2a_linkname=document.title;a2a_linkurl=location.href;</script><script type="text/javascript" src="http://static.addtoany.com/menu/page.js"></script></div>
                    <div id="entityList">
                    </div>
                </div>
            </td>
        </tr>
        <tr>
            <td style="width: 700px;">
                <div class="demo">

                    <span id="toolbar" class="ui-widget-header ui-corner-all">
                            <button id="beginning">go to beginning</button>
                            <button id="rewind">rewind</button>
                            <button id="play">play</button>
                            <button id="stop">stop</button>
                            <button id="forward">fast forward</button>
                            <button id="end">go to end</button>

                            <span id="repeat">
                                    <input type="checkbox" id="repeat" name="repeat" checked="checked" /><label for="repeat">Repeat</label>
<!--                                    <input type="radio" id="norepeat" name="repeat" /><label for="norepeat">Repeat</label>-->
<!--                                    <input type="radio" id="repeatall" name="repeat" /><label for="repeatall">All</label>-->
                            </span>

                            <label id="time"></label>
                    </span>

                </div><!-- End demo -->

            <div class="demo-description">
            <p>
                    A mediaplayer toolbar, code from <a href="http://jqueryui.com/demos/button/#toolbar">JQuery UI</a>.
                    Used to demonstrate the different scenarios possible with PlayMap.
            </p>
            <p>
                Continuous Play Map can be run on either live or replay, similar to a video and video feed.
                Information is passed to the widget as a table of values, specify which index is the time column, and the geometry column
                Use pushEntityData to specify data and display Options on an entity by entity level
                Use pushRawData to create on the fly entities by specifying the entity column in the table
                You can customise the appearance of your data on the map by specifying display options for each entities or for all.
            </p>
            </div><!-- End demo-description -->
            </td>
            <td>
            </td>
        </tr>
    </table>

<div class="js-kit-comments" backwards="yes" paginate="10"></div>
<script src="http://js-kit.com/comments.js"></script>

<script type="text/javascript">

    var map;
    var geocoder;
    var lastWindow;
    var playMapWidget;
    var examples = {
        "Satellite Orbits Replay": runSatelliteOrbit
//        "Boat Traffic Replay": runBoatsTraffic
    }
    var defaultIncrement = 60 * 1000;
    var shift =  75 * 60 * 1000;

    $('document').ready(initialize);

    /* INITIALIZE - initialize the map and geocoder */
    function initialize() {

            var beginning = $( "#beginning" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-seek-start"
                    }
            });
            var rewind = $( "#rewind" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-seek-prev"
                    }
            });
            var play = $( "#play" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-play"
                    }
            });
            var stop = $( "#stop" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-stop"
                    }
            });
            var forward = $( "#forward" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-seek-next"
                    }
            });
            var end = $( "#end" ).button({
                    text: false,
                    icons: {
                            primary: "ui-icon-seek-end"
                    }
            });
            var time = $("#time");
            var repeat = $( "span#repeat" ).buttonset();

            map = new google.maps.Map(document.getElementById('map_canvas'), {
                      center: new google.maps.LatLng(0.0, 0.0), //the center lat and long
                      zoom: 3, //zoom
                      mapTypeId: google.maps.MapTypeId.ROADMAP //the map style
                    });

            geocoder = new google.maps.Geocoder();

            playMapWidget = new playMap.ContinuousPlayMap(map, 1000.0);
            playMapWidget.setTimerIncrement(defaultIncrement);
            play.click(function() {
                    var options;
                    if ( $( this ).text() === "play" ) {
                            options = {
                                    label: "pause",
                                    icons: {
                                            primary: "ui-icon-pause"
                                    }
                            };
                        playMapWidget.play();
                    } else {
                            options = {
                                    label: "play",
                                    icons: {
                                            primary: "ui-icon-play"
                                    }
                            };
                        playMapWidget.pause();
                    }
                    $( this ).button( "option", options );
            });
            forward.click(function() {
                var increment = playMapWidget.getTimerIncrement();
                if(increment < -defaultIncrement) {
                    increment /= 2;
                } else if(increment == -defaultIncrement) {
                    increment = defaultIncrement;
                } else {
                    increment *= 2;
                }
                playMapWidget.setTimerIncrement(increment);
            });
            rewind.click(function() {
                var increment = playMapWidget.getTimerIncrement();
                if(increment > defaultIncrement) {
                    increment /= 2;
                } else if(increment == defaultIncrement) {
                    increment = -defaultIncrement;
                } else {
                    increment *= 2;
                }
                playMapWidget.setTimerIncrement(increment);
            });
            beginning.click(function() {
                var startTime = playMapWidget.getStartTime();
                playMapWidget.setCurrentTime(startTime + shift);
            });
            end.click(function() {
                var stopTime = playMapWidget.getStopTime();
                playMapWidget.setCurrentTime(stopTime);
            });
            stop.click(function() {
                $( "#play" ).button( "option", {
                        label: "play",
                        icons: {
                                primary: "ui-icon-play"
                        }
                });
                var startTime = playMapWidget.getStartTime();
                playMapWidget.pause();
                playMapWidget.setTimerIncrement(defaultIncrement);
                playMapWidget.setCurrentTime(startTime + shift);
                playMapWidget.setTimerIncrement(defaultIncrement);
            });
            // udpate time label
            playMapWidget.addEventListener(playMap.events.timeChanged,
                function(timeValue){
                    time.text(new Date(timeValue).toGMTString());
                });
            function getExample() {
                return $('#example').find('option:selected').val();
            }
            for(var exampleName in examples) {
                $('<option value="' + exampleName + '">' + exampleName + '</option>').appendTo($('#example'));
            }
            $('#example').change(function() {
                runExample(getExample());
            });
            runExample(getExample());
            var entityList = $('#entityList');
            playMapWidget.addEventListener(playMap.events.dataReady, function() {
                entityList.empty();
                var entities = playMapWidget.getEntities();
                var entityName;
                var entity;
                for(entityName in entities) {
                    entity = entities[entityName];
                    $(
                        '<h3><a href="#">' + entityName + '</a></h3>' +
                        '<div><ul class="smallIndent">' +
                            '<li><input id="visible" type="checkbox" checked="checked" name="' + entityName + '" />Visible</li>' +
                            '<li><input id="interpolated" type="checkbox" checked="checked" name="' + entityName + '" />Interpolated</li>' +
                            '<li><input id="trace" type="checkbox" name="' + entityName + '" />With Trace</li>' +
                            '<li><label>Trace length:</label><label id="traceLength"></label><div id="traceLength" name="' + entityName + '" /></li>' +
                        '</ul></div>'
                    ).appendTo(entityList);
                    playMapWidget.setDisplayOptions({interpolated: true, trace: false}, entityName);
                }
                entityList.find('input#visible').change(function() {
                    var checked = $(this).is(':checked');
                    var name = $(this).attr("name");
                    playMapWidget.setEntityVisibility(checked, name);
                });
                entityList.find('input#interpolated').change(function() {
                    var name = $(this).attr("name");
                    setOptions(name);
                });
                entityList.find('input#trace').change(function() {
                    var name = $(this).attr("name");
                    setOptions(name);
                });
                entityList.find('div#traceLength').slider({
			min: defaultIncrement / (60 * 1000),
			max: (playMapWidget.getStopTime() - playMapWidget.getStartTime()) / (60 * 1000),
			slide: function( event, ui ) {
                            var name = $(this).attr("name");
                            $('label#traceLength').text(ui.value + 'mns');
                            setOptions(name);
			}
                });
                function setOptions(entityName) {
                    playMapWidget.setDisplayOptions(
                    {
                        'interpolated': $('input#interpolated[name="' + entityName + '"]').is(':checked'),
                        trace: {on: $('input#trace[name="' + entityName + '"]').is(':checked'), length: $('div#traceLength[name="' + entityName + '"]').slider("value") * 60 * 1000}
                    }, entityName);
                }
                entityList.accordion();
            });
            playMapWidget.addEventListener(playMap.events.endOfData, function() {
                if($("input#repeat").is(':checked')) {
                    playMapWidget.setCurrentTime(playMapWidget.getStartTime() + shift);
                }
            });
    }

    function getOptions(entityName) {
        var trace = $('input#trace[name="' + entityName + '"]');
        var interpolated = $('#interpolated[name="' + entityName + '"]');
        return {
            traces: {on: trace.is(':checked')},
            interpolated: interpolated.is(':checked')
        };
    }

    function runExample(example) {
        playMapWidget.cleanUp();
        (examples[example] || function(){})();
    }

    // displays satellites orbitting with their traces and their positions interpolated
    // each satellite has an icon
    function runSatelliteOrbit() {
        var interpolated = $('#interpolated');
        interpolated.attr("checked", "checked");
        var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT Name, Start, Position FROM 432647"));
        query.send(function(response) {
                var satelliteIcons = {'ENVISAT': '27386', 'LANDSAT 7': '23560', 'SPOT 5': '00000', 'QUIKSCAT': '00000', 'default': '33331'};
                var entityIndex = 0;
                var options = {}; //getOptions();
                options.type = {type: "imageOverlay",
                                options: {
                                    image: function(data) {return ('http://www.n2yo.com/img/icons/' + (satelliteIcons[data[entityIndex]] || satelliteIcons['default']) + '.gif');},
                                    info: function(data) {return 'Satellite Name: ' + data[entityIndex] + '</br>Position: ' + data[2]}
                                }};
                pushFTData(response, 1, 2, 0, options);
            });
        map.setZoom(1);
        playMapWidget.addEventListener(playMap.events.dataReady, function() {
            playMapWidget.setCurrentTime(playMapWidget.getStartTime() + shift);
        });
    }

    // displays boats navigating with their traces and their positions interpolated
    // each boat has an icon which indicates its heading
    function runBoatsTraffic() {
//        var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT Text, Number, Location, Date FROM 420307"));
//        query.send(function(response) {
//                var options;
//                pushFTData(response, 3, 2, 0, options);
//            });
        alert('Coming soon!');
    }

    // displays RT boats traffic with their traces and their positions interpolated
    // each boat has an icon which indicates its heading
    function runRTBoatsTraffic() {
        var query = new google.visualization.Query('http://www.google.com/fusiontables/gvizdata?tq=' + encodeURIComponent("SELECT Text, Number, Location, Date FROM 420307"));
        query.send(function(response) {
                var options = getOptions();
                pushFTData(response, 3, 2, 0, options);
            });
    }

    function infoWindow(rowData) {
            return rowData[0] + ' ' + rowData[1];
    }

    /* GVIZ - get data from Fusion Tables */

    //define callback function, this is called when the results are returned
    function pushFTData(response, timeIndex, geometryIndex, entityIndex, options, geocoded) {

      //for more information on the response object, see the documentation
      //http://code.google.com/apis/visualization/documentation/reference.html#QueryResponse
      var numRows = response.getDataTable().getNumberOfRows();
      var numCols = response.getDataTable().getNumberOfColumns();

      var data = [];
      //create an array of row values
      for (i = 0; i < numRows; i++) {
        var row = [];
        for (j = 0; j < numCols; j++) {
          row.push(response.getDataTable().getValue(i, j));
        }
        data.push(row);
      }
      playMapWidget.pushData(entityIndex, data, timeIndex, geometryIndex, options);
    }

    /* GEOCODING - geocode data in Fusion Tables, if the data is a String Address */

    //geocode the address
    function geocodeRow(row, geometryIndex) {
      geocoder.geocode( { 'address': row[geometryIndex] }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          var coordinate = results[0].geometry.location;
          row[geometryIndex] = coordinate;
        }
      });
    }

</script>

    <script type="text/javascript">

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-11445983-8']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();

    </script>

  </body>
</html>
